package cn.dankal.flyaudio

import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import api.UserServiceFactory
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.pojo.UserInfoBean
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.util.SharePreferenceManager
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.statubar.QMUIStatusBarHelper
import cn.dankal.business.Constants
import cn.dankal.business.eventbus.OFFLoginEvent
import cn.dankal.flyaudio.friend.utils.FileHelper
import cn.dankal.flyaudio.home.ActivityFragment
import cn.dankal.flyaudio.home.CurrentFragment
import cn.dankal.flyaudio.home.HomeFragment
import cn.dankal.flyaudio.home.InformationFragment
import cn.dankal.flyaudio.login.LoginActivity
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.event.LoginStateChangeEvent
import cn.jpush.im.api.BasicCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayout
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import com.yzq.zxinglibrary.common.Constant
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Field

class MainActivity : BaseActivity() {

    override fun getLayoutId(): Int = R.layout.activity_main

    lateinit var commonDialog: CommonDialog
    private var dialog: Dialog? = null


    override fun initComponents() {
        //        setContentView(R.layout.activity_base);
        //注册sdk的event用于接收各种event事件
        JMessageClient.registerEventReceiver(this)

        EventBus.getDefault().post(OFFLoginEvent())

        DankalApplication.setLogin(true)
        val currentUser = SharePreferenceManager.getCurrentUser()
//        TestData.setUser(currentUser)


        if (!DKUserManager.isLogined()) {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
            return
        }


        mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
        // Set up the ViewPager with the sections adapter.
        container.adapter = mSectionsPagerAdapter
        container.offscreenPageLimit = 5
        container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
        //tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
        tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    // 默认切换的时候，会有一个过渡动画，设为false后，取消动画，直接显示
                    container.setCurrentItem(tab.getPosition(), false)
                    container.setCurrentItem(tab.getPosition())
                }
            }
        })

        container.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                when (position) {
                    Constants.ITEM_HOME -> {
                        QMUIStatusBarHelper.setStatusBarLightMode(this@MainActivity)
                    }
                    Constants.ITEM_ACTIVITY -> {
                        QMUIStatusBarHelper.setStatusBarLightMode(this@MainActivity)
                    }
                    Constants.ITEM_INFORMATION -> {
                        QMUIStatusBarHelper.setStatusBarLightMode(this@MainActivity)
                    }
                    Constants.ITEM_CURRENT -> {
                        QMUIStatusBarHelper.setStatusBarLightMode(this@MainActivity)
                    }
                    Constants.ITEM_MINE -> {
                        if (!DankalApplication.isLogin()) {
                            ARouter.getInstance().build(LoginProtocol.LOGIN).navigation()
                        } else
                            QMUIStatusBarHelper.setStatusBarDarkMode(this@MainActivity)
                    }
                }
            }
        })


        requestPermission()

        getUserInfo()
        /** 拦截tablayout点击事件 */
        val tabOnClickListener = View.OnTouchListener { view, event ->
            val pos = view.tag as Int
            if (pos == Constants.ITEM_MINE && event.action == MotionEvent.ACTION_DOWN && !DankalApplication.isLogin()) {
                ARouter.getInstance().build(LoginProtocol.LOGIN).navigation()
                return@OnTouchListener true
            }
            false // 不拦截
        }
        for (i in 0 until tabs.tabCount) {
            val view = getTabView(tabs, i) ?: continue
            view.tag = i
            view.setOnTouchListener(tabOnClickListener)
        }
    }

    fun onEventMainThread(event: LoginStateChangeEvent) {
        val reason = event.reason
        val myInfo = event.myInfo
        if (myInfo != null) {
            val path: String
            val avatar = myInfo.avatarFile
            path = if (avatar != null && avatar.exists()) {
                avatar.absolutePath
            } else {
                FileHelper.getUserAvatarPath(myInfo.userName)
            }
            SharePreferenceManager.setCachedUsername(myInfo.userName)
            SharePreferenceManager.setCachedAvatarPath(path)
            JMessageClient.logout()
        }
        when (reason) {
            LoginStateChangeEvent.Reason.user_logout -> {
                tokenInvalid()
            }
            LoginStateChangeEvent.Reason.user_password_change -> {
                val intent = Intent(this@MainActivity, LoginActivity::class.java)
                startActivity(intent)
            }
        }
    }

    /**
     * 获取个人用户信息
     */
    private fun getUserInfo() {
        if (DKUserManager.isLogined()) {
            UserServiceFactory.user_info()
                    .subscribe(object : AbstractDialogSubscriber<UserInfoBean>(this) {
                        override fun onNext(userInfo: UserInfoBean) {
                            DKUserManager.updateUserInfo(userInfo)
                        }

                        override fun onSubscribe(d: Disposable) {
                        }
                    })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        //注销消息接收
        JMessageClient.unRegisterEventReceiver(this)
        super.onDestroy()
    }

    /** 反射获取tabview  */
    private fun getTabView(tabLayout: TabLayout, index: Int): View? {
        val tab = tabLayout.getTabAt(index) ?: return null
        var tabView: View? = null
        try {
            val view: Field = TabLayout.Tab::class.java.getDeclaredField("mView")
            view.isAccessible = true
            tabView = view.get(tab) as View
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return tabView
    }

    private fun requestPermission() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CALL_PHONE, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)
                .onDenied {
                    val builder = CommonDialog.Builder(this)
                    builder.setTitle("禁止飞歌获取权限会影响到您的正常使用")

                    builder.setNegativeButton("残忍拒绝",
                            resources.getColor(R.color.color14)) {
                        ToastUtils.showShort("获取权限失败，请到设置中手动开启权限")
                        postDelayedToFinish()
                        commonDialog.dismiss()
                    }
                    builder.setPositiveButton("同意开启",
                            resources.getColor(R.color.colorPrimary)) {
                        toSelfSetting()
                        commonDialog.dismiss()
                    }
                    commonDialog = builder.create()
                    commonDialog.show()
                }.start()
    }

    private fun toSelfSetting() {
        var mIntent = Intent()
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", this.getPackageName(), null))
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW)
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
            mIntent.putExtra("com.android.settings.ApplicationPkgName", this.getPackageName())
        }
        startActivity(mIntent)
    }

    private var mSectionsPagerAdapter: SectionsPagerAdapter? = null

    override fun initStatusBar() {

    }

    inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            when (position) {
                Constants.ITEM_HOME -> {
                    return CurrentFragment()
                }
                Constants.ITEM_ACTIVITY -> {
                    return ActivityFragment.newInstance()
                }
                Constants.ITEM_INFORMATION -> {
                    return InformationFragment.newInstance()
                }
                Constants.ITEM_CURRENT -> {
                    return CurrentFragment.newInstance()
                }
                Constants.ITEM_MINE -> {
                    return CurrentFragment()
                }
            }
            return HomeFragment.newInstance()
        }

        override fun getCount(): Int {
            // Show 3 total pages.
            return 5
        }
    }

    fun select(position: Int) {
        container.setCurrentItem(position, true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constants.SCAN && resultCode == RESULT_OK && data != null) {

            //扫码内容
            val result = data.getStringExtra(Constant.CODED_CONTENT)

            if (result.contains("native://cn.dankal.flyaudio/activityid=")) {
                val resultValue = result.split("native://cn.dankal.flyaudio/activityid=")[1]
                ARouter.getInstance().build(MainProtocol.ACTIVITY_DETAIL)
                        .withString(Constants.UUID, resultValue)
                        .navigation()
                return
            } else {
                showToast("暂无相关信息")
            }
        }
    }
}
